<!DOCTYPE html>
<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org">
<head th:include="/include/commonHeader::commonHeader('机组排班')"></head>
<body class="gray-bg layer-blue">
<script src="/js/jquery-ui.min.js"></script>
<div class="wrapper wrapper-content animated fadeInRight full-container">
    <div class="row" id="container">
        <div class="col-xs-7">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <div class="btn-group table-tool" id="table1-toolbar" role="group">
                        <i class="fa fa-arrow-left" onclick="changeDate(-1,'#flightDate')"
                           style="position:absolute;left:0;top:0;padding:8px 6px;color:#1c84c6;cursor:pointer;"></i>

                        <input type="text" placeholder="请选择日期" style="width:120px;"
                               class="table-tool-btn pull-left text-center" id="flightDate"/>
                        <i class="fa fa-arrow-right" onclick="changeDate(1,'#flightDate')"
                           style="position:absolute;left:98px;top:0;padding:8px 6px;color:#1c84c6;cursor:pointer;"></i>
                        <input type="text" placeholder="请输入航班号" style="width:120px;" id="flightCom"
                               class="table-tool-btn pull-left"/>
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="筛选" id="btn-search">筛选
                        </button>
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="刷新" id="btn-refresh">刷新
                        </button>
                    </div>
                    <div class="btn-group table-tool pull-right" id="table2-toolbar" role="group">
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="生效" id="btn-confirm">
                            生效
                        </button>
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="清除" id="btn-clear">
                            清除
                        </button>
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="初始化号位" id="btn-initPosition">
                            初始化号位
                        </button>
                        <button type="button" class="btn btn-outline btn-success btn-refresh" data-toggle="tooltip"
                                title="自动排班" id="btn-auto">
                            自动排班
                        </button>
                        <!--<div id="auto-assign-div" class="pull-left" style="position:relative;">
                            <input type="text" placeholder="开始日期" style="width:85px;border-left:none;"
                                   class="table-tool-btn pull-left text-center" id="autoStartDate"/>
                            <span class="pull-left" style="display:inline-block;border-top:1px solid #1c84c6;border-bottom:1px solid #1c84c6;line-height:26px;">-</span>
                            <input type="text" placeholder="结束日期"
                                   style="width:145px;border-left:none;padding-right:70px;border-right:1px solid #1c84c6;border-top-right-radius:3px;border-bottom-right-radius:3px;"
                                   class="table-tool-btn pull-left text-center" id="autoEndDate"/>
                            <span class="btn btn-outline btn-success btn-refresh"
                                    title="自动排班" id="btn-auto" style="font-size:10px;">
                                自动排班
                            </span>
                        </div>-->
                    </div>
                    <table id="table" data-classes="table table-hover table-condensed">
                        <thead>
                        <tr>
                            <th data-field="id" data-formatter="orderFormatter" data-width="40" data-valign="middle" data-halign="center">序号</th>
                            <th data-field="acInfo" data-formatter="acInfoFormatter" data-valign="middle" data-halign="center">机号<br>机型</th>
                            <th data-field="flight"  data-formatter="flightFormatter" data-valign="middle" data-halign="center">连线</th>
                            <th data-field="loopName" data-formatter="preferenceFormatter" data-valign="middle" data-halign="center">任务</th>
                            <th data-field="time" data-formatter="flightTimeFormatter"  data-width="40" data-valign="middle" data-halign="center">起飞<br>到达</th>
                            <th data-field="interval" data-formatter="intervalFormatter"  data-width="40" data-valign="middle" data-halign="center">飞行<br>执勤</th>

                            <th th:if="${dutyCode =='F'}" data-field="captainList" data-formatter="personEditFormatter" data-valign="middle" data-halign="center">机长 <i class="fa fa-plus text-success" onclick="addPerson('captainList')" style="cursor:pointer;"></i></th>
                            <th th:if="${dutyCode =='F'}"  data-field="fristCopilot" data-formatter="personEditFormatter" data-valign="middle" data-halign="center">一副 <i class="fa fa-plus text-success" onclick="addPerson('fristCopilot')" style="cursor:pointer;"></i></th>
                            <th th:if="${dutyCode =='F'}"  data-field="secondCopilot" data-formatter="personEditFormatter" data-valign="middle" data-halign="center">二副 <i class="fa fa-plus text-success" onclick="addPerson('secondCopilot')" style="cursor:pointer;"></i></th>

                            <th th:if="${dutyCode =='C'}" data-field="cabin1" data-formatter="personEditFormatter" data-valign="middle" data-halign="center">乘务长 <i class="fa fa-plus text-success" onclick="addPerson('cabin1')" style="cursor:pointer;"></i></th>
                            <th th:if="${dutyCode =='C'}"  data-field="cabin2" data-formatter="personEditFormatter" data-valign="middle" data-halign="center">两舱 <i class="fa fa-plus text-success" onclick="addPerson('cabin2')" style="cursor:pointer;"></i></th>
                            <th th:if="${dutyCode =='C'}"  data-field="cabin3" data-formatter="personEditFormatter" data-valign="middle" data-halign="center">乘务员 <i class="fa fa-plus text-success" onclick="addPerson('cabin3')" style="cursor:pointer;"></i></th>

                            <th data-field="ruleVerificationSummary.verificationResultLevel" data-formatter="verificationFormatter" data-valign="middle" data-halign="center">规则分析</th>
                        </tr>
                        </thead>

                    </table>
                </div>
            </div>
        </div>
        <div class="col-xs-5" th:include="/include/commonPerson::commonPerson"></div>
    </div>
    <div class="row">
        <div th:include="/include/commonCrewLinkLine::commonCrewLinkLine"></div>
    </div>
</div>
<!--修改岗位科目弹窗-->
<div class="wrapper wrapper-content layer-body" id="layerBody" style="display:none;">
    <form class="form-horizontal" id="user_edit_form">
        <div class="row person-item">
            <div class="col-xs-9 col-xs-offset-1">
                <div class="form-group">
                    <div class="col-xs-3 form-label-v">
                        <label>岗位:</label>
                    </div>
                    <div class="text-left col-xs-9">
                        <select class="position" id="position"></select>
                    </div>
                </div>
                <div class="form-group"  th:if="${dutyCode =='F'}">
                    <div class="col-xs-3 form-label-v">
                        <label>科目:</label>
                    </div>
                    <div class="text-left col-xs-9">
                        <select class="subject" id="subject"></select>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<!--自动排班选择日期弹窗-->
<div class="wrapper wrapper-content layer-body" id="autoAssighLayerBody" style="display:none;">
    <form class="form-horizontal" id="date_edit_form">
        <div class="row person-item">
            <div class="col-xs-9 col-xs-offset-1">
                <div class="form-group">
                    <div class="col-xs-4 form-label-v">
                        <label>开始日期:</label>
                    </div>
                    <div class="text-left col-xs-8">
                        <input type="text" class="form-control"  id="autoStartDate"/>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-xs-4 form-label-v">
                        <label>结束日期:</label>
                    </div>
                    <div class="text-left col-xs-8">
                        <input type="text"  class="form-control" id="autoEndDate"/>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<div id="mask">
    <div id="content" class="fullwidth">
        <span class="expand"></span>
        <label class="text">正在自动排班中，请稍后。。。</label>
    </div>
</div>
<script src="/js/jquery-ui-resizeReverse.js"></script>
<script th:inline="javascript">

    var dutyCode = [[${dutyCode}]];//dutyCode

    var columnsArray = [];
    var tablePersonTaskData = []; //某人进一个月的任务安排
    var personData = []; //人员数据
    var personSelectData = [];//人员数据
    var isAutoAssign = false;//是否自动排班
    var url = '/';
    var rankNoData = {
        "captainList": "A001",
        "fristCopilot": "C001",
        "secondCopilot": "C002",
        "cabin1": "H001",
        "cabin2": "H003",
        "cabin3": "H003",
    }
    var positionData = getAjaxData({url: '/pilotAssign/getTsFlag',data:{dutyCode:dutyCode}});
    var subjectData = getAjaxData({url: '/pilotAssign/getCheckThing',data:{dutyCode:dutyCode}});
    var docHeight = $(document).height(); //内容区域高度，根据百分比计算排班管理高度
    var dayAfter = 10; //机组某人员近一个月任务安排，今天前20天，今天后10天
    var timer = null; //自动排班表格人员单击双击冲突延时器
    var verificationResultData ={
        0:'正常',
        1:'告警',
        2:'违规'
    };
    var verificationResultColor = {
        0:'#1ab394',
        1:'#f8ac59',
        2:'#ed5565'
    }
    $(document).ready(function () {
        $.fn.select2.defaults.set("theme", "bootstrap"); //使用select2-bootstrap主题
        //日期初始化
        $("#flightDate").datetimepicker({
            minView: "month",
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            bootcssVer: 3,
            todayHighlight: true,
            pickerPosition: "bottom-right"
        }).on('changeDate', function (ev) {
            initTable();
            initTablePerson();
            initTablePersonTask();
        });
        $("#flightDate").datetimepicker('setDate', new Date()).trigger('change');
        $("#autoStartDate").datetimepicker({
            minView: "month",
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            bootcssVer: 3,
            todayHighlight: true,
            pickerPosition: "bottom-right"
        }).on('changeDate', function (ev) {
            $("#autoEndDate").datetimepicker('setStartDate', $("#autoStartDate").val());
        });
        $("#autoEndDate").datetimepicker({
            minView: "month",
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayBtn: true,
            bootcssVer: 3,
            todayHighlight: true,
            pickerPosition: "bottom-right"
        }).on('changeDate', function (ev) {
            $("#autoStartDate").datetimepicker("setEndDate", $("#autoEndDate").val());
        });

        $("#autoStartDate").datetimepicker('setDate', new Date()).trigger('change');
        $("#autoEndDate").datetimepicker('setDate', new Date()).trigger('change');

        initTablePerson();
        //人员任务历史初始化
        initTablePersonTask();

        //排班表格初始化
        initTable();

        //人员管理初始化
        $(".time-filter").on("click", function (event) {
            event.stopPropagation();
        });
        $("#btn-search-person,#btn-filter-person").click(function () {
            searchPerson();
        });
        $("#btn-reset-person").click(function () {
            //清空数据，加载原来的数据，不请求后台
            resetSearchPerson();
        });

        $("#btn-search").click(function () {
            var data = $("#table").bootstrapTable("getData");
            var flightCom = $("#flightCom").val();
            var position = 0;
            $("#table tr").removeClass("info");
            if (flightCom) {
                if (data) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].flightCom.indexOf(flightCom) > -1) {
                            position = $("#table tr[data-uniqueid='" + data[i].crewLinkLineId + "']").position().top - $("#table thead").height();
                            $("#table tr[data-uniqueid='" + data[i].crewLinkLineId + "']").addClass("info");
                            break;
                        }
                    }
                }
                position = position + $("#table").bootstrapTable("getScrollPosition");
            }
            $("#table").bootstrapTable("scrollTo", position);
        });
        //自动排版
        $("#btn-auto").click(function () {
            layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                area: ['400px', '250px'],
                btn: ["保存", "取消"],
                zIndex: 999,
                title: "自动排班",
                content: $("#autoAssighLayerBody"),
                yes: function (indexLayer, layero) {
                    autoAssign(indexLayer);
                },
                cancel: function (indexLayer, layero) {
                },
                success: function (indexLayer, index) {
                    //数据显示

                }
            });

        });
        //清除排班人员
        $("#btn-clear").click(function () {
            $.ajax({
                url: "/pilotAssign/clear",
                dataType: 'json',
                cache: false,
                data: {flightDate: $("#flightDate").val(),dutyCode:dutyCode},
                success: function (data) {
                    if (!data.errorCode && (data.success == 'true' || data.success == true)) {
                        toastr.success('清除排班成功！');
                        initTable();
                    } else {
                        toastr.error('数据加载失败，请联系信息中心！');
                    }
                },
                error: function (data) {
                    toastr.error('数据加载失败，请联系信息中心！');
                }
            });
        });

        //初始化号位
        $("#btn-initPosition").click(function () {
            $.ajax({
                url: "/pilotAssign/initPositon",
                dataType: 'json',
                cache: false,
                data: {flightDateStart: $("#flightDate").val(),flightDateEnd: $("#flightDate").val(),dutyCode:dutyCode},
                success: function (data) {
                    if (!data.errorCode && (data.success == 'true' || data.success == true)) {
                        toastr.success('初始化号位成功！');
                        initTable();
                    } else {
                        toastr.error('数据加载失败，请联系信息中心！');
                    }
                },
                error: function (data) {
                    toastr.error('数据加载失败，请联系信息中心！');
                }
            });
        });

        //生效排班人员
        $("#btn-confirm").click(function () {
            $.ajax({
                url: "/pilotAssign/confirm",
                dataType: 'json',
                cache: false,
                data: {flightDate: $("#flightDate").val(),dutyCode:dutyCode},
                success: function (data) {
                    if (!data.errorCode && (data.success == 'true' || data.success == true)) {
                        toastr.success('排班生效成功！');
                        initTable();
                    } else {
                        toastr.error('数据加载失败，请联系信息中心！');
                    }
                },
                error: function (data) {
                    toastr.error('数据加载失败，请联系信息中心！');
                }
            });
        });
        $(window).resize(function () {
            $('#table').bootstrapTable('resetView');
            $('#table-person').bootstrapTable('resetView');
        });

        $("#btn-refresh").click(function () {
            //清空参数，重新请求后台
            $("#table").bootstrapTable("refresh");
        })
        $("#btn-refresh-person").click(function () {
            //清空参数，重新请求后台
            $("#person-name").val("");
            $("#person-tech").val("");
            $("#person-loc").val("");
            $(".time-filter-start").val("");
            $(".time-filter-end").val("");
            $("#table-person").bootstrapTable("refresh");
        });
        //人员菜单隐藏
        $(document).on("mousedown", function (event) {
            //button等于0代表左键，button等于1代表中键
            if ((event.button == 0 || event.button == 1) && (!$(event.target).hasClass('personDiv'))) {
                /* $(".editableform").cancel();//获取菜单停止动画，进行隐藏使用淡出效果,未使用动画*/
                $(".editableform").parent().triggerHandler('cancel');
            }
        });


    });

    //自动排班
    function autoAssign(indexLayer) {
        //请求中
        $("#mask").show();
        isAutoAssign = true;
        $.ajax({
            url: url + "pilotAssign/autoAssign",
            dataType: 'json',
            cache: false,
            data: {flightDateStart: $("#autoStartDate").val(),flightDateEnd:$("#autoEndDate").val(),dutyCode:dutyCode},
            success: function (data) {
                if (!data.errorCode && (data.success == 'true' || data.success == true)) {
                    $("#mask").hide();
                    toastr.success('自动排班成功！');
                    initTable();
                    layer.close(indexLayer);
                } else {
                    $("#mask").hide();
                    toastr.error('数据加载失败，请联系信息中心！');
                }
            },
            error: function (data) {
                $("#mask").hide();
                toastr.error('数据加载失败，请联系信息中心！');
            }
        });
    }


    //机组排班表格初始化
    function initTable() {
        $("#table").bootstrapTable("destroy").bootstrapTable({
            url: "/pilotAssign/getLinkLineDate",
            clickToSelect: true,
            singleSelect: true,
            showRefresh: false,                  //是否显示刷新按钮
            striped: true,//行间隔色
            locale: "${language}",
            uniqueId: 'crewLinkLineId',
            height: docHeight * 0.75,
            queryParams: function (params) {
                var result = {
                    flightDate: $("#flightDate").val(),
                    dutyCode:dutyCode
                };
                return result;
            },
            onClickRow: function (row, $element, field) {
                $element.addClass("info").siblings().removeClass("info");
            },
            onLoadSuccess: function (data) {
                //单元格可接收拖拽
                dropInit();
                $(".drop-field").click(function () {
                    $(".drop-field").removeClass("active-df");
                    $(this).addClass("active-df");
                    //人员近一个月任务记录
                    var self = $(this);
                    $("#table-person tr").removeClass("info");
                    clearTimeout(timer);
                    if (self.data("person")) {
                        timer = setTimeout(function() {
                            searchPersonByWorkcode(true, self.data("workcode"), self.data("cname"));
                            $("#table-person tr[data-uniqueid=" + self.data('workcode') + "]").addClass("info");
                            var rowPositionTop = $("#table-person tr[data-uniqueid=" + self.data('workcode') + "]").position().top - $("#table-person thead").height()
                            var position = rowPositionTop + $("#table-person").bootstrapTable("getScrollPosition");
                            $("#table-person").bootstrapTable("scrollTo", position);
                        },250);
                    } else {
                        timer = setTimeout(function() {
                            searchPersonByWorkcode(true, '', '');
                            $("#table-person").bootstrapTable("scrollTo", 0);
                        },250);
                    }
                });
                if (!isAutoAssign) {
                    personSelectData = [];
                    for (var i = 0; i < personData.length; i++) {
                        var temp = {};
                        temp.id = personData[i].workcode;
                        temp.text = personData[i].cName;
                        temp.pyAbbr = personData[i].pyAbbr;
                        temp.tech = personData[i].techZName;
                        personSelectData.push(temp);
                    }
                    isAutoAssign = false;
                }
            },
        });



    }

    //获取人员排班信息
    function getCrewLinkLineByDate(code) {
        var result = [];
        var endDate = addDate($("#flightDate").val(), dayAfter);
        var startDate = addDate($("#flightDate").val(), -(30 - dayAfter));
        $.ajax({
            url: url + "pilotAssign/listSchedule",
            dataType: 'json',
            async: false,
            cache: false,
            data: {startDate: startDate, endDate: endDate, workcode: code},
            success: function (data) {
                result = data;
            },
            error: function (data) {
                result = [];
            }
        });
        return result;
    }

    //起飞落地时间初始化
    function tFormatter(value, row, index) {
        if (!value) {
            return '';
        } else {
            if (value.split(" ")[1]) {
                var res = value.split(" ")[1].substring(0, 5);
                return res;
            } else {
                return '';
            }
        }

    }

    //权限
    function operateFormatter(value, row, index) {
        return [
            '&nbsp;&nbsp;',
            '<a class="edit ml10" href="javascript:void(0)" title="编辑">',
            '<span class="glyphicon glyphicon-edit "></span>',
            '</a>',
            '&nbsp;&nbsp;',
            '<a class="delete ml10" href="javascript:void(0)" title="删除">',
            '<span class="glyphicon glyphicon-trash text-danger"></span>',
            '</a>',
        ].join('');
    }

    function addDate(date, days) {
        var d = new Date(date);
        d.setDate(d.getDate() + days);
        var m = (d.getMonth() + 1) > 9 ? (d.getMonth() + 1) : '0' + (d.getMonth() + 1);
        var day = d.getDate() > 9 ? d.getDate() : '0' + d.getDate();
        return d.getFullYear() + '-' + m + '-' + day;
    }

    function operatePerson(dom) {
        if ($(dom).hasClass("fa-plus-circle")) {
            $(dom).removeClass("fa-plus-circle").addClass("fa-minus-circle");
            $(".person-item").removeClass("hide");
        } else {
            $(dom).parents(".person-item").addClass("hide");
            $(dom).parents(".person-item").siblings().find(".fa").removeClass("fa-minus-circle").addClass("fa-plus-circle");
        }
    }

    //获取人员信息
    function getAjaxData(param) {
        var result = [];
        $.ajax({
            url: param.url,
            dataType: 'json',
            async: false,
            cache: false,
            data: param.data ? param.data : {},
            success: function (data) {
                result = data;
            },
            error: function (data) {
                result = [];
            }
        });
        return result;
    }

    function setPerson(dom) {
        clearTimeout(timer);
        var isCabinNo1 = false;
        var isCabinNo2 = false;
        if(dutyCode == "C"){
            //当前操作的岗位
            if($(dom).data("no") == "1"){
                isCabinNo1 = true;
            }
            if($(dom).data("no") == "2"){
                isCabinNo2 = true;
            }
        }
        if (!$(dom).data("person")) {
            if(isCabinNo1){
                if (!$("#toast-container")[0]) {
                    toastr.warning("乘务长1号位，不可删除！");
                }
                return false;
            }
            if(isCabinNo2){
                if (!$("#toast-container")[0]) {
                    toastr.warning("两舱2号位，不可删除！");
                }
                return false;
            }
            layer.confirm('确认删除该号位吗?', function(index){
                layer.close(index);
                delPerson(dom);
            });
        }else{
            layer.open({
                type: 1,
                skin: 'layui-layer-demo', //样式类名
                area: ['400px', '30%'],
                btn: ["保存", "删除", "取消"],
                zIndex: 999,
                title: "修改岗位",
                content: $("#layerBody"),
                yes: function (index, layero) {
                    //保存修改
                    var positionId = $(dom).data("positionid");
                    var rankNo = rankNoData[$(dom).parents(".person-info-ul").data("field")];
                    var crewLinkLineId = $(dom).parents("tr").data("uniqueid");
                    var rowData = $("#table").bootstrapTable("getRowByUniqueId", crewLinkLineId);
                    var workcode = $(dom).data("workcode");
                    var param = {
                        positionId: positionId,
                        workcode: workcode,
                        crewLinkLineNo: rowData.crewLinkLineNo,
                        flightDate: $("#flightDate").val(),
                        dutyCode: rowData.dutyCode,
                        rankNo: rankNo,
                        serialNo: $(dom).data("no"),
                        tsFlag: $("#position").val(),
                        checkThing: $("#subject").val()
                    }
                    //update
                    $.ajax({
                        url: url + "pilotAssign/updatePosition",
                        dataType: 'json',
                        data: param,
                        success: function (data) {
                            if (data.success == true || data.success == 'true') {
                                toastr.success(data.message);
                                layer.close(index);
                                $(dom).data("tsflag",$("#position").val());
                                $(dom).data("checkthing",$("#subject").val());
                                var positionText = $.trim($("#position option:selected").text()).substr(0,1);
                                $(dom).text($(dom).text()+positionText);
                            } else {
                                toastr.error(data.message);
                            }
                        },
                        error: function (data) {
                            toastr.error("请求出错！");
                        }
                    });

                },
                btn2: function (index, layero) {
                    //按钮【按钮二】的回调
                    if(isCabinNo1){
                        if (!$("#toast-container")[0]) {
                            toastr.warning("乘务长1号位，不可删除！");
                        }
                        return false;
                    }
                    if(isCabinNo2){
                        if (!$("#toast-container")[0]) {
                            toastr.warning("两舱2号位，不可删除！");
                        }
                        return false;
                    }
                    delPerson(dom);

                    //return false 开启该代码可禁止点击该按钮关闭
                },
                btn3: function (index, layero) {
                    //按钮【按钮三】的回调
                    return true;
                    //return false 开启该代码可禁止点击该按钮关闭
                },
                cancel: function () {
                    //右上角关闭回调

                    //return false 开启该代码可禁止点击该按钮关闭
                },
                success: function (indexLayer, index) {
                    //下拉菜单初始化
                    initLayerSelect();
                    //数据赋值
                    $("#number").val($(dom).data("no")).trigger("change");
                    $("#position").val($(dom).data("tsflag")).trigger("change");
                    $("#subject").val($(dom).data("checkthing")).trigger("change");

                }
            });
        }

    }

    function choosePosition() {
        layer.open({
            type: 1,
            skin: 'layui-layer-demo', //样式类名
            area: ['40%', '30%'],
            btn: ["保存", "取消"],
            zIndex: 999,
            title: "修改岗位",
            content: $("#layerBody"),
            yes: function (indexLayer, layero) {
            },
            cancel: function (indexLayer, layero) {
            },
            success: function (indexLayer, index) {
                //数据显示
                $(".position").select2({
                    minimumResultsForSearch: Infinity,
                    data: positionData,
                    width: "100%"
                });
            }
        });
    }

    //人员显示格式化
    function personEditFormatter(value, row, index, field) {
        var data = row[field];
        var html = '';
        if (data) {
            html += '<ul class="list-unstyled person-info-ul ' + field + '" data-field="' + field + '">';
            for (var i = 0; i < data.length; i++) {
                var personText = '暂无';
                var dataPerson = false; //号位有人 true 无人 fasle
                if (data[i].crewInfoForAssign) {
                    dataPerson = true;
                    personText = data[i].crewInfoForAssign.cName + '-' + data[i].crewInfoForAssign.techZName + '-';
                }
                html += '<li class="border-bottom drop-field" data-no="' + data[i].position.serialNo +
                    '" data-positionid="' + data[i].position.positionId +
                    '" data-tsflag="' + data[i].position.TsFlag;
                if (dataPerson) {
                    html += '" data-workcode="' + data[i].position.workcode +
                        '" data-cname="' + data[i].crewInfoForAssign.cName;
                }
                html += '" data-checkthing="' + data[i].position.checkThing +
                    '" data-person="' + dataPerson + '" ondblclick="setPerson(this)">' +
                    data[i].position.serialNo + '-' + personText + '</li>';
            }
        }

        return html;
    }

    //规则分析结果格式化
    function verificationFormatter(value, row, index, field){
        if(!isNaN(parseInt(value))){
            return '<span style="padding:1px 5px;color:#fff;cursor:pointer;background:'+verificationResultColor[value]+'" onclick=showVerificationDetail("'+row.crewLinkLineNo+'")>'+verificationResultData[value]+'</span>';
        }else{
            return '';
        }

    }
    function addPerson(type) {
        //var selectRow = $("#table").bootstrapTable("getSelections");
        var crewLinkLine = $("#table tr.info");
        var rowData = $("#table").bootstrapTable("getRowByUniqueId", crewLinkLine.data("uniqueid"));
        if (crewLinkLine.length == 0) {
            if (!$("#toast-container")[0]) {
                toastr.warning("请先选择连线！");
            }
            return false;
        }
        //乘务长只有1号位 两舱只有2号位
        if(dutyCode == "C"){
            //当前操作的岗位
            var persons = crewLinkLine.find("td ul."+type+" li");
            if(persons.length == 1){
                if($(persons[0]).data("no") == "1"){
                    if (!$("#toast-container")[0]) {
                        toastr.warning("乘务长1号位已存在，不可添加！");
                    }
                    return false;
                }
                if($(persons[0]).data("no") == "2"){
                    if (!$("#toast-container")[0]) {
                        toastr.warning("两舱2号位已存在，不可添加！");
                    }
                    return false;
                }

            }
        }
        $.ajax({
            url: url + "pilotAssign/getPosition",
            dataType: 'json',
            data: {
                crewLinkLineNo: rowData.crewLinkLineNo,
                flightDate: $("#flightDate").val(),
                rankNo: rankNoData[type],
                dutyCode:dutyCode
            },
            success: function (data) {
                if (data.success == true || data.success == 'true') {
                    toastr.success(data.message);
                    var html = '<li class="border-bottom drop-field" data-person="false" data-positionid="' + data.data.positionId +
                        '" data-no="' + data.data.serialNo + '"  ondblclick="setPerson(this)">' + data.data.serialNo + '-暂无</li>';
                    var ulDom = crewLinkLine.find("ul." + type).append(html);
                    addPersonInit(ulDom.find("li[data-no="+data.data.serialNo+"]"));
                    $('#table').bootstrapTable('resetView');
                } else {
                    toastr.error(data.message);
                }
            },
            error: function (data) {
                toastr.error("请求出错！");
            }
        });
    }

    function delPerson(dom) {
        $.ajax({
            url: url + "pilotAssign/deletePosition",
            dataType: 'json',
            data: {positionId: $(dom).data("positionid")},
            success: function (data) {
                if (data.success == true || data.success == 'true') {
                    toastr.success(data.message);
                    $(dom).remove();
                    $('#table').bootstrapTable('resetView');
                } else {
                    toastr.error(data.message);
                }
            },
            error: function (data) {
                toastr.error("请求出错！");
            }
        });

    }

    function searchPersonByWorkcode(flag, workcode, name) {
        var personTaskData = getCrewLinkLineByDate(workcode);
        tablePersonTaskData = [];
        var dataItem = {};
        for (var i = 0; i < columnsArray.length; i++) {
            var tempTask = '';
            for (var j = 0; j < personTaskData.length; j++) {
                if (columnsArray[i].field == personTaskData[j].date.substr(5, 5)) {
                    tempTask += personTaskData[j].scheduleContent;
                }
            }
            dataItem[columnsArray[i].field] = tempTask;
            dataItem.cName = name;
        }

        tablePersonTaskData.push(dataItem);
        if (!flag) {
            //flag true 点击人员表格查询，false点击人员下拉选择查询
            $("#table-person").bootstrapTable("resetSearch", workcode);
        }
        $("#table-person-task").bootstrapTable("load", tablePersonTaskData);
    }

    //任务高亮格式化
    function loopNameFormatter(value, row, index, field) {
        var loop = row.linkLineLoopFact;
        var loopArr = loop.loopName.split("-");
        var html = '';
        for (var i = 0; i < loopArr.length; i++) {
            if (loopArr[i].indexOf(row.flightVoyage) > -1) {
                html += '<div class="active">' + loopArr[i] + '</div>';
            } else {
                html += '<div>' + loopArr[i] + '</div>';
            }
        }
        return html;

    }

    //任务环列隐藏显示，hover提示
    function preferenceFormatter(value, row, index) {
        var nameString = "";
        var loopName = row.loopName;
        if (loopName.length > 6) {
            nameString = loopName.substring(0, 6) + '...';
        } else {
            nameString = loopName;
        }
        return [
            '<a href="javascript:void(0)" style="color:#676a6c;" data-toggle="tooltip"  data-placement="bottom" title=' + loopName + '>' + nameString + '</a>',
        ].join('');
    }

    function flightTimeFormatter(value, row, index) {
        return moment(row.td).format("HH:mm") + "<br>" + moment(row.ta).format("HH:mm");
    }
    function intervalFormatter(value, row, index) {
        return moment(row.td).format("HH:mm") + "<br>" + moment(row.ta).format("HH:mm");
    }
    function flightFormatter(value, row, index) {
        return row.flightCom + '<br>' + row.flightVoyage;
    }
    function acInfoFormatter(value, row, index){
        return row.acReg + '<br>' + row.acType;
    }

    function initLayerSelect() {
        $("#position").select2({
            minimumResultsForSearch: Infinity,
            data: positionData,
            allowClear: true,
            placeholder: "--请选择--",
            width: "100%"
        });
        $("#subject").select2({
            minimumResultsForSearch: Infinity,
            data: subjectData,
            allowClear: true,
            placeholder: "--请选择--",
            width: "100%"
        });
        //号位不可为空  添加人员时  默认号位为1
        $("#position,#subject").val(null).trigger('change');
    }

    function dropInit(dom) {
        var initDom = '';
        if(dom){
            initDom = $(dom);
        }else{
            initDom =  $('#table tbody td li.drop-field');
        }
        initDom.droppable({
            over: function (event, ui) {
                var thisDom = $(this);
                $(".drop-field").removeClass("active-df");
                thisDom.addClass("active-df")
            },
            drop: function (event, ui) {
                var source = ui.draggable.clone(); //draggable info
                var workcode = source.data("uniqueid");
                var thisDom = $(this);

                if (workcode) {
                    //获取拖拽人员信息
                    var rowPersonData = $('#table-person').bootstrapTable("getRowByUniqueId", workcode);
                    var rankNo = rankNoData[thisDom.parents(".person-info-ul").data("field")];
                    //号位 no
                    var serialNo = thisDom.data("no");
                    //获取排班表格行数据
                    var rowCrewLinkLineId = thisDom.parents("tr").data("uniqueid");
                    var rowData = $("#table").bootstrapTable("getRowByUniqueId", rowCrewLinkLineId);

                    var data = {
                        workcode: workcode,
                        crewLinkLineNo: rowData.crewLinkLineNo,
                        flightDate: rowData.flightDate.substring(0, 10),
                        dutyCode: rowData.dutyCode,
                        rankNo: rankNo,
                        serialNo: serialNo,
                        positionId: thisDom.data("positionid")
                    }
                    //add
                    $.ajax({
                        url: url + "pilotAssign/savePosition",
                        dataType: 'json',
                        data: data,
                        success: function (data) {
                            var parentDom = thisDom.parent();
                            if (data.success == true || data.success == 'true') {
                                toastr.success(data.message);
                                var personText = rowPersonData.cName + '-' + rowPersonData.techZName + '-';
                                var html = '<li class="border-bottom drop-field" data-no="' + data.data.serialNo +
                                    '" data-positionid="' + data.data.positionId +
                                    '"  data-tsflag="' + data.data.TsFlag +
                                    '"  data-cname="' + rowPersonData.cName +
                                    '"  data-workcode="' + data.data.workcode +
                                    '" data-checkthing="' + data.data.checkThing +
                                    '"  data-person="true" ondblclick="setPerson(this)">' + data.data.serialNo + '-' + personText + '</li>';
                                parentDom.find("li[data-no="+data.data.serialNo+"]").remove();
                                parentDom.append(html);
                                addPersonInit(parentDom.find("li[data-no="+data.data.serialNo+"]"));
                                $('#table').bootstrapTable('resetView');
                            } else {
                                toastr.error(data.message);
                            }
                        },
                        error: function (data) {
                            toastr.error("请求出错！");
                        }
                    });
                }
            }
        });
    }

    function addPersonFromPersonList(row) {
        var selectPosition = $("#table li.active-df");
        var selectPositionParent = selectPosition.parents(".person-info-ul");
        if (selectPosition.length == 0) {
            if (!$("#toast-container")[0]) {
                toastr.warning("请先选择排班号位！");
            }
            return;
        }
        var rankNo = rankNoData[selectPositionParent.data("field")];
        //号位 no
        var serialNo = selectPosition.data("no");
        //获取排班表格行数据
        var rowCrewLinkLineId = selectPosition.parents("tr").data("uniqueid");
        var rowData = $("#table").bootstrapTable("getRowByUniqueId", rowCrewLinkLineId);
        var data = {
            workcode: row.workcode,
            crewLinkLineNo: rowData.crewLinkLineNo,
            flightDate: row.flightDate.substring(0, 10),
            dutyCode: row.dutyCode,
            rankNo: rankNo,
            serialNo: serialNo,
            positionId: selectPosition.data("positionid")
        }
        //add
        $.ajax({
            url: url + "pilotAssign/savePosition",
            dataType: 'json',
            data: data,
            success: function (data) {
                if (data.success == true || data.success == 'true') {
                    toastr.success(data.message);
                    var personText = row.cName + '-' + row.techZName + '-';
                    var html = '<li class="border-bottom drop-field" data-no="' + data.data.serialNo +
                        '" data-positionid="' + data.data.positionId +
                        '"  data-tsflag="' + data.data.TsFlag +
                        '"  data-cname="' + row.cName +
                        '"  data-workcode="' + data.data.workcode +
                        '" data-checkthing="' + data.data.checkThing +
                        '"  data-person="true" ondblclick="setPerson(this)">' + data.data.serialNo + '-' + personText + '</li>';
                    selectPositionParent.find("li[data-no="+data.data.serialNo+"]").remove();
                    selectPositionParent.append(html);
                    addPersonInit(selectPositionParent.find("li[data-no="+data.data.serialNo+"]"));
                    $('#table').bootstrapTable('resetView');
                } else {
                    toastr.error(data.message);
                }
            },
            error: function (data) {
                toastr.error("请求出错！");
            }
        });
    }

    function addPersonInit(dom){
        dropInit(dom);
        $(dom).click(function () {
            $(".drop-field").removeClass("active-df");
            $(dom).addClass("active-df");
            //人员近一个月任务记录
            var self = $(dom);
            $("#table-person tr").removeClass("info");
            clearTimeout(timer);
            if (self.data("person")) {
                timer = setTimeout(function(){
                    searchPersonByWorkcode(true, self.data("workcode"), self.data("cname"));
                    $("#table-person tr[data-uniqueid="+self.data('workcode')+"]").addClass("info");
                    var rowPositionTop = $("#table-person tr[data-uniqueid="+self.data('workcode')+"]").position().top - $("#table-person thead").height()
                    var position = rowPositionTop + $("#table-person").bootstrapTable("getScrollPosition");
                    $("#table-person").bootstrapTable("scrollTo", position);
                },250);

            } else {
                timer = setTimeout(function(){
                    searchPersonByWorkcode(true, '', '');
                    $("#table-person").bootstrapTable("scrollTo", 0);
                },250);
            }
        });
    }
    function showVerificationDetail(crewLinkLineNo){
        layer.open({
            type: 2,
            skin: 'layui-layer-demo', //样式类名
            area: ['80%', '80%'],
            zIndex: 999,
            title: "规则详情",
            content: '/pilotAssign/toVerificationDetailPage.do?crewLinkLineNo='+crewLinkLineNo+'&flightDate='+$("#flightDate").val()+'&dutyCode='+dutyCode,
        });
    }
</script>
</body>
</html>